package com.hundsun.yr.universal.p2p.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.library.widget.SwitchButton;
import com.hundsun.yr.universal.p2p.bean.AutoBidInfoBean;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.keyboard.KeyboardTouchListener;
import com.hundsun.yr.universal.p2p.keyboard.KeyboardUtil;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.HashMap;

import static com.hundsun.yr.universal.p2p.config.TaskConstants.TASK_BIDSIGN;

/**
 * Created by xx on 2017/7/7.
 * 自动投标
 */
public class AutoBidAuthActivity extends BaseActivity implements InitializeView, View.OnClickListener, ViewCreatorHelper.UpdateItem, CompoundButton.OnCheckedChangeListener, HSDialog.HSDialogOnItemClickListener {
    private RequestPresenter mPresenter;
    private String zwgt_data;
    private AutoBidInfoBean mAutoBidInfoBean;

    /**
     * 签约
     **/
    private HSDialog dialog_bindcard = null;

    //-------------------------------------------------------------------------------------------------------------------

    /**
     * 投资金额
     */
    private LinearLayout linear_invest_amount;

    /**
     * 投资期限
     */
    private LinearLayout linear_invest_term;

    /**
     * 年化收益率
     */
    private LinearLayout linear_year_rate;

    /**
     * 自动投标开关
     */
    private SwitchButton switchb_setgesturepass;
    private SwitchButton switchb_use_discount;
    private SwitchButton switchb_auto_bid_ask;

    /**
     * 投资规则的情况
     */
    private TextView tv_invest_amount;
    private TextView tv_invest_term;
    private TextView tv_invest_rate;

    private HSEditText et_vcode = null;

    private int SETTINGAUTOBID = 1;
    private int SETTINGINVESTAMOUNT = 2;
    private int SETTINGPAYMETHOD = 3;
    private int SETTINGINVESTTERM = 4;
    private int SETTINGYEARRATE = 5;
    private int SETTINGAUTOSIGN = 6;

    //所有的数据
    String minamount = "";
    String maxamount = "";
    String minrate = "";
    String maxrate = "";
    String minterm = "";
    String maxterm = "";
    String discountflag = "";
    String openflag = "";
    //    String allinflag = "";
    String smsflag = "";
    private HSDialog dialog;
    private HSDialog sureDialog;
    private String progress;
    private boolean cancelFlag = false;
    private String isTouchButton = "-1";

    /**
     * 到期还本付息
     */
    private CheckBox cb_paymethod1 = null;

    /**
     * 按月先息后本
     */
    private CheckBox cb_paymethod2 = null;

    /**
     * 按月等额本息
     */
    private CheckBox cb_paymethod3 = null;

    /**
     * 按月等额本金
     */
    private CheckBox cb_paymethod4 = null;

    /**
     * 保存设置
     */
    private HSButton btn_auto_bid_sure = null;

    /**
     * 投标方法拼接
     */
    private String paymethod = "";
    private String paymethod1 = "";
    private String paymethod2 = "";
    private String paymethod3 = "";
    private String paymethod4 = "";
    private PopupWindow popWindow;
    private KeyboardUtil keyboardUtil;


    @Override
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_autobidauth;
    }

    @Override
    protected void initViewsAndEvents() {
//        btn_vcode = findView(R.id.btn_vcode);
        //----------------------------------------------------------找一波控件
        et_vcode = findView(R.id.et_vcode);
//        linear_automatic_bid_advanced_settings = findView(R.id.linear_automatic_bid_advanced_settings);
        switchb_setgesturepass = findView(R.id.switchb_setgesturepass);
        switchb_use_discount = findView(R.id.switchb_use_discount);
        switchb_auto_bid_ask = findView(R.id.switchb_auto_bid_ask);

//        tv_call_phone = findView(R.id.tv_call_phone);

        //投资金额  还款方式  投资期限  年化收益率
        linear_invest_amount = findView(R.id.linear_invest_amount);
//        linear_paymethod = findView(R.id.linear_paymethod);
        linear_invest_term = findView(R.id.linear_invest_term);
        linear_year_rate = findView(R.id.linear_year_rate);

        tv_invest_amount = findView(R.id.tv_invest_amount);
//        tv_pay_method = findView(R.id.tv_pay_method);
        tv_invest_term = findView(R.id.tv_invest_term);
        tv_invest_rate = findView(R.id.tv_invest_rate);

        cb_paymethod1 = findView(R.id.cb_paymethod1);
        cb_paymethod2 = findView(R.id.cb_paymethod2);
        cb_paymethod3 = findView(R.id.cb_paymethod3);
        cb_paymethod4 = findView(R.id.cb_paymethod4);
        btn_auto_bid_sure = findView(R.id.btn_auto_bid_sure);

        //----------------------------------------------------------------------获取首次点击自动投标按钮获取的用户设定数据
        if (mAutoBidInfoBean.min_amount != null && !mAutoBidInfoBean.min_amount.isEmpty()) {
            minamount = mAutoBidInfoBean.min_amount;
        }

        if (mAutoBidInfoBean.max_amount != null && !mAutoBidInfoBean.max_amount.isEmpty()) {
            maxamount = mAutoBidInfoBean.max_amount;
        }

        if (mAutoBidInfoBean.pay_method != null && !mAutoBidInfoBean.pay_method.isEmpty()) {
            paymethod = mAutoBidInfoBean.pay_method;
        }

        if (mAutoBidInfoBean.min_rate != null && !mAutoBidInfoBean.min_rate.isEmpty()) {
            minrate = mAutoBidInfoBean.min_rate;
        }

        if (mAutoBidInfoBean.max_rate != null && !mAutoBidInfoBean.max_rate.isEmpty()) {
            maxrate = mAutoBidInfoBean.max_rate;
        }

        if (mAutoBidInfoBean.min_term != null && !mAutoBidInfoBean.min_term.isEmpty()) {
            minterm = mAutoBidInfoBean.min_term;
        }

        if (mAutoBidInfoBean.max_term != null && !mAutoBidInfoBean.max_term.isEmpty()) {
            maxterm = mAutoBidInfoBean.max_term;
        }

        if (mAutoBidInfoBean.if_usediscount != null && !mAutoBidInfoBean.if_usediscount.isEmpty()) {
            discountflag = mAutoBidInfoBean.if_usediscount;
        }

        if (mAutoBidInfoBean.if_open != null && !mAutoBidInfoBean.if_open.isEmpty()) {
            openflag = mAutoBidInfoBean.if_open;
        }

        if (mAutoBidInfoBean.if_sendsms != null && !mAutoBidInfoBean.if_sendsms.isEmpty()) {
            smsflag = mAutoBidInfoBean.if_sendsms;
        }

        progress = mAutoBidInfoBean.progress;

        //------------------------------------------------------------------赋值数据
        //投资金额
        tv_invest_amount.setText(getString(R.string.invest_amount_, CommTool.moneyOneThousandsFormat(minamount), CommTool.moneyOneThousandsFormat(maxamount)));
        //投资期限
        tv_invest_term.setText(getString(R.string.credit_term, minterm, maxterm));
        //投资利率
        tv_invest_rate.setText(CommTool.formartPercent1(Double.valueOf(minrate).doubleValue()) + "~" + CommTool.formartPercent1(Double.valueOf(maxrate).doubleValue()));

        //开启状态
        if (TextUtils.equals(openflag, "1")) {
            switchb_setgesturepass.setChecked(true);
        } else {
            switchb_setgesturepass.setChecked(false);
        }

        //优惠卷使用状态
        if (TextUtils.equals(discountflag, "1")) {
            switchb_use_discount.setChecked(true);
        } else {
            switchb_use_discount.setChecked(false);
        }

        //是否开启短信提醒
        if (TextUtils.equals(smsflag, "1")) {
            switchb_auto_bid_ask.setChecked(true);
        } else {
            switchb_auto_bid_ask.setChecked(false);
        }
        //所有按钮的监听-------------------------------------------------------------------

        //开启或者关闭自动投标
        switchb_setgesturepass.setOnCheckedChangeListener(this);
        switchb_use_discount.setOnCheckedChangeListener(this);
        switchb_auto_bid_ask.setOnCheckedChangeListener(this);

        linear_invest_amount.setOnClickListener(this);
        linear_invest_term.setOnClickListener(this);
        linear_year_rate.setOnClickListener(this);

        //P层逻辑的初始化
        mPresenter = new InitializePresenterImpl(mContext, this);
        toolbar_title.setText(getString(R.string.mine_automatic_bid));

        /**
         * 将网络获取的还款方式展示出来
         */
        String[] split = paymethod.split(",");
        for (String s : split) {
            if (TextUtils.equals(s, "1")) {
                cb_paymethod1.setChecked(true);
                paymethod1 = "1";
            } else if (TextUtils.equals(s, "2")) {
                cb_paymethod2.setChecked(true);
                paymethod2 = "2";
            } else if (TextUtils.equals(s, "3")) {
                cb_paymethod3.setChecked(true);
                paymethod3 = "3";
            } else if (TextUtils.equals(s, "4")) {
                cb_paymethod4.setChecked(true);
                paymethod4 = "4";
            }
        }

        cb_paymethod1.setOnCheckedChangeListener(this);
        cb_paymethod2.setOnCheckedChangeListener(this);
        cb_paymethod3.setOnCheckedChangeListener(this);
        cb_paymethod4.setOnCheckedChangeListener(this);

        btn_auto_bid_sure.setOnClickListener(this);
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    /**
     * 网络请求--进行投标规则的提交
     */
    public void loadingData() {
        showProgress("");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                JSONObject map = new JSONObject();
                try {
                    map.put("minamount", minamount);
                    map.put("maxamount", maxamount);
                    map.put("paymethod", paymethod);
                    map.put("minrate", minrate);
                    map.put("maxrate", maxrate);
                    map.put("minterm", minterm);
                    map.put("maxterm", maxterm);
                    map.put("discountflag", discountflag);
                    map.put("openflag", openflag);
                    map.put("smsflag", smsflag);
                    Logs.e("minamount" + minamount + ",maxamount" + maxamount + ",paymethod" + paymethod + ",minrate" + minrate + ",maxrate" + maxrate + ",minterm" + minterm + ",maxterm" + maxterm + ",discountflag" + discountflag + ",openflag" + openflag + "smsflag" + smsflag);

                } catch (Exception e) {
                    e.printStackTrace();
                }

                JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                mPresenter.loadingData(TASK_BIDSIGN, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test)
                        + TASK_BIDSIGN, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test)
                        + TASK_BIDSIGN, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
            }
        }, 500);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        mAutoBidInfoBean = (AutoBidInfoBean) extras.getSerializable("autoBidAuthBean");
    }

    @Override
    protected void onEveComming(EventCenter eventCenter) {
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
        switch (task_name) {
            case TASK_BIDSIGN:
                showToast("投标规则修改成功");
                finish();
                break;

            case TaskConstants.TASK_AUTOBIDINFO:
                AutoBidInfoBean mAutoBidInfoBean = (AutoBidInfoBean) data;
                progress = mAutoBidInfoBean.progress;
                break;

            case TaskConstants.TASK_SETBANKPWD://设置交易密码
                if (data == null) {
                    return;
                }

                UpdatePayPwdBeen mUpdatePayPwdBeen = (UpdatePayPwdBeen) data;

                //现在做另外一种操作
                String postData = null;
                try {
                    postData = "accountId=" + URLEncoder.encode(mUpdatePayPwdBeen.data.accountId.toString(), "utf-8") + "&acqRes=" + URLEncoder.encode(mUpdatePayPwdBeen.data.acqRes.toString(), "utf-8") +
                            "&bankCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.bankCode.toString(), "utf-8") + "&channel=" + URLEncoder.encode(mUpdatePayPwdBeen.data.channel.toString(), "utf-8") +
                            "&idNo=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idNo.toString(), "utf-8") + "&idType=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idType.toString(), "utf-8") + "&instCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.instCode.toString(), "utf-8") + "&lastSrvAuthCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.lastSrvAuthCode == null ? "" : mUpdatePayPwdBeen.data.lastSrvAuthCode.toString(), "utf-8") +
                            "&mobile=" + URLEncoder.encode(mUpdatePayPwdBeen.data.mobile.toString(), "utf-8") + "&name=" + URLEncoder.encode(mUpdatePayPwdBeen.data.name.toString(), "utf-8") + "&notifyUrl=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.notifyUrl.toString(), "utf-8") + "&retUrl=" + URLEncoder.encode(mUpdatePayPwdBeen.data.retUrl.toString(), "utf-8") + "&seqNo=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.seqNo.toString(), "utf-8") + "&sign=" + URLEncoder.encode(mUpdatePayPwdBeen.data.sign.toString(), "utf-8") + "&smsCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.smsCode == null ? "" : mUpdatePayPwdBeen.data.smsCode.toString(), "utf-8") + "&txCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txCode.toString(), "utf-8") +
                            "&txDate=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txDate.toString(), "utf-8") + "&txTime=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txTime.toString(), "utf-8") + "&version=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.version.toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.set_paywd));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, mUpdatePayPwdBeen.url);
                bundle.putString(BaseWebActivity.BUNDLE_KEY_PARAMS, postData);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.POSTDATA.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGoThenKill(WebSetPasswordActivity.class, bundle);
                break;
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    @Override
    public void onClick(View view) {
        if (isFastDoubleClick()) {
            return;
        }

        switch (view.getId()) {
            case R.id.linear_invest_amount://投资金额
                showPopup(toolbar_title, 0);
                break;

            case R.id.linear_invest_term://投资期限
                showPopup(toolbar_title, 1);
                break;

            case R.id.linear_year_rate://投资年利率
                showPopup(toolbar_title, 2);
                break;

            case R.id.btn_auto_bid_sure://保存设置
                if (getPaymethod().isEmpty()){
                    showToast(getString(R.string._repayment_method));
                    return;
                }
//                getPaymethod();
                loadingData();
                break;
        }
    }

    @Override
    public void refreshItem(View view, int i, Object o) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean ischeck) {
        switch (compoundButton.getId()) {
            case R.id.switchb_setgesturepass:
                if (cancelFlag) {
                    cancelFlag = false;
                    return;
                }
                if (ischeck) {
                    openflag = "1";
                    if (!TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_PAYPWD), "YES")) {
                        //未设置交易密码
                        switchb_setgesturepass.setChecked(false);
                        openflag = "0";
                        showToast("您尚未设置交易密码");
//                        zwgt_data = BaseRequestTool2.getFormatedDateString();
//                        JSONObject map = new JSONObject();
//
//                        try {
//                            map.put("vcode", "");
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
                         readyGo(ManagementActivity.class);
//                        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
//                        mPresenter.loadingData(TaskConstants.TASK_SETBANKPWD, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, Constants.EVENT_DATA,
//                                jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_user_test) + TaskConstants.TASK_SETBANKPWD, sharedPreferences
//                                        .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                        return;
                    }

                    if (sharedPreferences.getShareProf(UserInfo.USERLEVEL) != null && TextUtils.equals(sharedPreferences.getShareProf(UserInfo.USERLEVEL), "0")) {
                        switchb_setgesturepass.setChecked(false);
                        openflag = "0";
                        dialog = new HSDialog(getString(R.string.risk_login), getString(R.string.no_risk_assessment),
                                getString(R.string.no_investment), getString(R.string.evaluate_immediately), mContext, this).setCancelable(false);
                        dialog.show();
                        return;
                    }

                    if (TextUtils.equals(progress, "0") || TextUtils.equals(progress, "1")) {
                        dialog_bindcard = new HSDialog(getString(R.string.tips), "您尚未进行自动投标签约",
                                getString(R.string.cancel), getString(R.string.sure), mContext,
                                this).setCancelable(false);//.setOnDismissListener(this);
                        dialog_bindcard.show();

                        switchb_setgesturepass.setChecked(false);
                        openflag = "0";
                        return;
                    }
                } else {
                    sureDialog = new HSDialog(getString(R.string.tips), "确定关闭自动投标？",
                            getString(R.string.cancel), getString(R.string.sure), mContext,
                            this).setCancelable(false);//.setOnDismissListener(this);
                    sureDialog.show();
                }
                break;
            case R.id.switchb_use_discount:
                if (ischeck) {
                    discountflag = "1";
                } else {
                    discountflag = "0";
                }
//                loadingData();
                break;
            case R.id.switchb_auto_bid_ask:
                if (ischeck) {
                    smsflag = "1";
                } else {
                    smsflag = "0";
                }
//                loadingData();
                break;

            //还款方式
            case R.id.cb_paymethod1:
                if (ischeck) {
                    paymethod1 = "1";
                } else {
                    paymethod1 = "";
                }
                break;
            case R.id.cb_paymethod2:
                if (ischeck) {
                    paymethod2 = "2";
                } else {
                    paymethod2 = "";
                }
                break;
            case R.id.cb_paymethod3:
                if (ischeck) {
                    paymethod3 = "3";
                } else {
                    paymethod3 = "";
                }
                break;
            case R.id.cb_paymethod4:
                if (ischeck) {
                    paymethod4 = "4";
                } else {
                    paymethod4 = "";
                }
                break;
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        if ((HSDialog) o == dialog_bindcard) {
            if (position != -1) {
                readyGoForResult(AutoBidSignActiviy.class, SETTINGAUTOSIGN);
            } else {
                cancelFlag = false;
                switchb_setgesturepass.setChecked(false);
            }
        } else if ((HSDialog) o == dialog) {
            if (position != -1) {
                //展示风险评估h5页面
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        TaskConstants.TASK_RISKESTIMATE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap = new HeaderMap();
                headerMap.setMap(hearder);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.risk_estimate));
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_RISKESTIMATE);
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebRiskActivity.class, bundle);
            } else {
                cancelFlag = false;
                switchb_setgesturepass.setChecked(false);
            }
        } else if ((HSDialog) o == sureDialog) {
            if (position != -1) {
                openflag = "0";
//                loadingData();
            } else {
                openflag = "1";
                cancelFlag = true;
                switchb_setgesturepass.setChecked(true);
            }
        }
    }


    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (sureDialog != null && sureDialog.isShowing()) {
                cancelFlag = true;
                sureDialog.dismiss();
                return true;
            }

            if (dialog_bindcard != null && dialog_bindcard.isShowing()) {
                cancelFlag = false;
                dialog_bindcard.dismiss();
                return true;
            }

            if (dialog != null && dialog.isShowing()) {
                cancelFlag = false;
                dialog.dismiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public String getPaymethod() {
        String[] a = {paymethod1, paymethod2, paymethod3, paymethod4};
        StringBuffer sp = new StringBuffer();
        for (String s : a) {
            if (!s.isEmpty()) {
                sp.append(s + ",");
            }
        }

        paymethod = sp + "";

        if (paymethod.endsWith(",")) {
            paymethod = paymethod.substring(0, paymethod.length() - 1);
        }
        return paymethod;
    }

    /**
     * 创建PopupWindow对象
     *
     * @param parent
     */
    @SuppressLint({"InflateParams", "WrongConstant"})
    private void showPopup(View parent, int pop_num) {
        backgroundAlpha((float) 0.5);
        LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = layoutInflater.inflate(R.layout.pop_auto_bid_parameter, null);
        if (popWindow == null) {
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
        }

        TextView tv_pop_title = findView(view, R.id.tv_pop_title);
        final HSEditText hset_min = findView(view, R.id.hset_min);
        final HSEditText hset_max = findView(view, R.id.hset_max);
        TextView tv_min_unit = findView(view, R.id.tv_min_unit);
        TextView tv_max_unit = findView(view, R.id.tv_max_unit);
        TextView tv_pop_message = findView(view, R.id.tv_pop_message);
        ScrollView scrollView = findView(R.id.pop_scrollview);

        keyboardUtil = new KeyboardUtil(view, mContext, (LinearLayout) view, scrollView);
        //软键盘变化的监听
        keyboardUtil.setKeyBoardStateChangeListener(new KeyBoardStateListener());
        //软键盘关闭或者下一步的监听
        keyboardUtil.setInputOverListener(new InputOverListener());

        hset_min.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_FINISH, -1));
        hset_max.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_FINISH, -1));

        //让前面不能输入零
        hset_min.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (hset_min.toString().equals("0") || s.toString().startsWith("0")) {
                    hset_min.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        hset_max.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (hset_max.toString().equals("0") || s.toString().startsWith("0")) {
                    hset_max.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        switch (pop_num) {
            case 0:
                tv_pop_title.setText(getString(R.string.investment_amount));
                tv_min_unit.setText(getString(R.string.yuan));
                tv_max_unit.setText(getString(R.string.yuan));
                tv_pop_message.setText(getString(R.string.min_amount_and_max_amount));

                hset_min.setHint("1000");
                hset_max.setHint("1000000");

                if (!minamount.isEmpty()){
                    hset_min.setText((int) MathUtils.string2double(minamount) + "");
                }

                if (!maxamount.isEmpty()){
                    hset_max.setText((int) MathUtils.string2double(maxamount) + "");
                }

                // 确认按钮的监听
                keyboardUtil.setInputSureListener(new KeyboardUtil.InputSureListener() {
                    @Override
                    public void inputHasSure(int onclickType, EditText editText) {
                        String minamount = hset_min.getText().toString();
                        String maxamount = hset_max.getText().toString();
                        if (minamount.isEmpty()){
                            showToast("请输入最小投资金额");
                            return;
                        }

                        if (maxamount.isEmpty()){
                            showToast("请输入最大投资金额");
                            return;
                        }

                        if (MathUtils.compare(minamount,"1000") < 0){
                            showToast("最小投资金额不能小于1000元");
                            return;
                        }

                        if (MathUtils.compare(maxamount,"1000000") > 0){
                            showToast("最大投资金额为100万元");
                            return;
                        }

                        if (MathUtils.compare(minamount,maxamount) > 0){
                            showToast("最小投资金额不能大于最大投资金额");
                            return;
                        }

                        AutoBidAuthActivity.this.minamount = minamount;
                        AutoBidAuthActivity.this.maxamount = maxamount;
                        tv_invest_amount.setText(getString(R.string.invest_amount_, CommTool.moneyOneThousandsFormat(minamount), CommTool.moneyOneThousandsFormat(maxamount)));

                        keyboardUtil.hideKeyboardLayout();
                        popWindow.dismiss();
                    }
                });
                break;
            case 1:
                tv_pop_title.setText(getString(R.string.investment_duration));
                tv_min_unit.setText(getString(R.string.day));
                tv_max_unit.setText(getString(R.string.day));
                tv_pop_message.setText(getString(R.string.min_term_and_max_term));

                hset_min.setHint("10");
                hset_max.setHint("360");

                if (!minterm.isEmpty()){
                    hset_min.setText(minterm);
                }

                if (!maxterm.isEmpty()){
                    hset_max.setText(maxterm);
                }

                // 确认按钮的监听
                keyboardUtil.setInputSureListener(new KeyboardUtil.InputSureListener() {
                    @Override
                    public void inputHasSure(int onclickType, EditText editText) {
                        String minterm = hset_min.getText().toString();
                        String maxterm = hset_max.getText().toString();

                        if (minterm.isEmpty()){
                            showToast("请输入最小投资期限");
                            return;
                        }

                        if (maxterm.isEmpty()){
                            showToast("请输入最大投资期限");
                            return;
                        }

                        if (MathUtils.compare(minterm,"10") < 0){
                            showToast("最小投资期限不能小于10天");
                            return;
                        }

                        if (MathUtils.compare(maxterm,"360") > 0){
                            showToast("最大投资期限不能超过360天");
                            return;
                        }

                        if (MathUtils.compare(minterm,maxterm) > 0){
                            showToast("您输入的最小投资期限，大于最大投资期限");
                            return;
                        }

                        AutoBidAuthActivity.this.minterm = minterm;
                        AutoBidAuthActivity.this.maxterm = maxterm;
                        tv_invest_term.setText(getString(R.string.credit_term, minterm, maxterm));

                        keyboardUtil.hideKeyboardLayout();
                        popWindow.dismiss();
                    }
                });
                break;
            case 2:
                tv_pop_title.setText(getString(R.string.expected_interestrate));
                tv_min_unit.setText(getString(R.string.percent));
                tv_max_unit.setText(getString(R.string.percent));
                tv_pop_message.setText(getString(R.string.min_annualized_income_and_max_annualized_income));

                hset_min.setHint("5");
                hset_max.setHint("15");

                if (!minrate.isEmpty()){
                    hset_min.setText(CommTool.formart1(Double.valueOf(minrate).doubleValue()));
                }

                if (!maxrate.isEmpty()){
                    hset_max.setText(CommTool.formart1(Double.valueOf(maxrate).doubleValue()));
                }

                // 确认按钮的监听
                keyboardUtil.setInputSureListener(new KeyboardUtil.InputSureListener() {
                    @Override
                    public void inputHasSure(int onclickType, EditText editText) {
                        String minrate = hset_min.getText().toString();
                        String maxrate = hset_max.getText().toString();
                        if (minrate.isEmpty()){
                            showToast("请输入最小年利率");
                            return;
                        }

                        if (maxrate.isEmpty()){
                            showToast("请输入最大年利率");
                            return;
                        }

                        if (MathUtils.compare(minrate,"5") < 0){
                            showToast("最小年利率为5");
                            return;
                        }

                        if (MathUtils.compare(maxrate,"15") > 0){
                            showToast("最大年利率为15");
                            return;
                        }

                        if (MathUtils.compare(minrate,maxrate) > 0){
                            showToast("您输入的最小年利率大于最大年利率");
                            return;
                        }

                        AutoBidAuthActivity.this.minrate = minrate;
                        AutoBidAuthActivity.this.maxrate = maxrate;
                        tv_invest_rate.setText(CommTool.formartPercent1(Double.valueOf(minrate).doubleValue()) + "~" + CommTool.formartPercent1(Double.valueOf(maxrate).doubleValue()));

                        keyboardUtil.hideKeyboardLayout();
                        popWindow.dismiss();
                    }
                });
                break;
        }


        popWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //popupwindow弹出时的动画
        popWindow.setAnimationStyle(R.style.project_pop_style);
        //监听菜单的关闭事件
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
//                InputMethodManager imm =  (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                hideSoftInputMethod(hset_min);
//                hideSoftInputMethod(hset_max);
                popWindow = null;
            }
        });

        popWindow.setTouchable(true);
        // 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
        popWindow.setFocusable(true);
        // 设置允许在外点击消失
        popWindow.setOutsideTouchable(true);
//        //监听触屏事件
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            public boolean onTouch(View view, MotionEvent event) {
                return false;
            }
        });
        popWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    public void hideSoftInputMethod(EditText ed) {

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


        int currentVersion = android.os.Build.VERSION.SDK_INT;

        String methodName = null;

        if (currentVersion >= 16) {

// 4.2

            methodName = "setShowSoftInputOnFocus";

        } else if (currentVersion >= 14) {

// 4.0

            methodName = "setSoftInputShownOnFocus";

        }


        if (methodName == null) {

            ed.setInputType(InputType.TYPE_NULL);

        } else {

            Class<EditText> cls = EditText.class;

            Method setShowSoftInputOnFocus;

            try {

                setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);

                setShowSoftInputOnFocus.setAccessible(true);

                setShowSoftInputOnFocus.invoke(ed, false);

            } catch (NoSuchMethodException e) {

                ed.setInputType(InputType.TYPE_NULL);

                e.printStackTrace();

            } catch (IllegalAccessException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            } catch (InvocationTargetException e) {

// TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

    }

    class KeyBoardStateListener implements KeyboardUtil.KeyBoardStateChangeListener {

        @Override
        public void KeyBoardStateChange(int state, EditText editText) {
        }
    }

    class InputOverListener implements KeyboardUtil.InputFinishListener {

        @Override
        public void inputHasOver(int onclickType, EditText editText) {
        }
    }
}
